package com.xiaoluo.service;

import com.xiaoluo.cd.dao.VersionMapper;
import com.xiaoluo.cd.entity.base.Version;
import com.xiaoluo.cd.entity.base.VersionExample;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Project : XL-CD
 * Package : com.xiaoluo.service
 * Created by Willian.
 * Date  : 2016/2/3 14:37.
 */
@Service
@Transactional
public class VersionService {
    private final static Logger logger = LoggerFactory.getLogger(VersionService.class);

    @Autowired
    private VersionMapper versionMapper;

    /**
     *
     * @param version
     */
    public void save(Version version){
        logger.info(version.getVersion());

        if(version.getId() != null){
            versionMapper.updateByPrimaryKey(version);
        }else {
            if(!isExist(version)){
                versionMapper.insert(version);
            }
        }
    }

    public boolean isExist(Version version){
        VersionExample example = new VersionExample();
        example.createCriteria().andVersionEqualTo(version.getVersion()).andProjIdEqualTo(version.getProjId());

        List<Version> versions = versionMapper.selectByExample(example);

        if(versions != null && versions.size() >0){
            return true;
        }else {
            return false;
        }
    }

    /**
     *
     * @param projId
     * @return
     */
    public List<Version> findByProj(Long projId){
        List<Version> result = new ArrayList<Version>();

        VersionExample example = new VersionExample();
        example.createCriteria().andProjIdEqualTo(projId);
        example.setOrderByClause("id desc");

        return versionMapper.selectByExample(example);
    }

    /**
     *
     * @param id
     * @return
     */
    public Version getVersion(Long id){
        return versionMapper.selectByPrimaryKey(id);
    }
}
